//
//  MovieFriendsViewController.m
//  觅影
//
//  Created by Zeus on 16/4/8.
//  Copyright © 2016年  陶虹. All rights reserved.
//

#import "MovieFriendsViewController.h"
#import "FriendsMainModel.h"
#import "FriendsMovieInfoModel.h"
#import "FriendsCell.h"
#import "FriendsHeaderView.h"
#import "AddFriendsViewController.h"
#import "MyFriendsViewController.h"
#import "PersonInfoViewController.h"

@interface MovieFriendsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, FriendsHeaderDelegate>
@property (nonatomic, strong) UISegmentedControl *segment;
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) NSMutableArray *moiveInfoModelArray;
@property (nonatomic, assign) NSInteger startPage;
@end

@implementation MovieFriendsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self addSegment];
    [self putUpView];
    
    if ([[NetWorkState shareInstance] reachability]) {
        [self netRequest];
    }else{
        [self reloadFromDB];
    }
    
}

- (NSMutableArray *)modelArray{
    if (!_modelArray) {
        self.modelArray = [NSMutableArray array];
    }
    return _modelArray;
}


- (void)reloadFromDB{
}

- (void)putUpView{
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"FriendsCell" bundle:nil] forCellWithReuseIdentifier:@"friendsCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"FriendsHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"friendsHeaderView"];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self netRequest];
    }];
    self.collectionView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [self netRequestMore];
    }];
    self.startPage = 1;
}

#pragma mark --- 网络请求 下拉刷新 ---
- (void)netRequest{
    // 默认请求10个
    [RequestManager requestWithUrl:@"http://static.v6v7.com/snowman_api/movie_traces/list_by_user?" requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = dic[@"result"][@"data"];
        [self.modelArray removeAllObjects];
        for (NSDictionary *dataDic in dataArray) {
            NSDictionary *userDic = dataDic[@"user"];
            FriendsMainModel *model = [[FriendsMainModel alloc] init];
            [model setValuesForKeysWithDictionary:userDic];
            
            model.movieArray = [NSMutableArray array];
            NSArray *ugclistArray = dataDic[@"ugc_list"];
            for (NSDictionary *ugclistDic in ugclistArray) {
                FriendsMovieInfoModel *movieModel = [[FriendsMovieInfoModel alloc] init];
                [movieModel setValuesForKeysWithDictionary:ugclistDic];
                [model.movieArray addObject:movieModel];
            }
            [self.modelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
            [self.collectionView.mj_header endRefreshing];
        });
        
    } error:^(NSError *error) {
        NSLog(@"影友列表网络请求失败");
    }];
}

#pragma mark --- 上拉加载 ---
- (void)netRequestMore{
    self.startPage ++;
    [RequestManager requestWithUrl:[NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/list_by_user?page=%ld&page_size=10", self.startPage] requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = dic[@"result"][@"data"];
        for (NSDictionary *dataDic in dataArray) {
            NSDictionary *userDic = dataDic[@"user"];
            FriendsMainModel *model = [[FriendsMainModel alloc] init];
            [model setValuesForKeysWithDictionary:userDic];
            
            model.movieArray = [NSMutableArray array];
            NSArray *ugclistArray = dataDic[@"ugc_list"];
            for (NSDictionary *ugclistDic in ugclistArray) {
                FriendsMovieInfoModel *movieModel = [[FriendsMovieInfoModel alloc] init];
                [movieModel setValuesForKeysWithDictionary:ugclistDic];
                [model.movieArray addObject:movieModel];
            }
            [self.modelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
            [self.collectionView.mj_footer endRefreshing];
        });

    } error:^(NSError *error) {
        NSLog(@"影友列表上拉加载请求数据失败");
    }];
}

- (void)addSegment{
    NSArray *titleArray = @[@"影友",@"好友"];
    self.segment = [[UISegmentedControl alloc] initWithItems:titleArray];
    self.segment.frame = CGRectMake((KWIDTH - 120) / 2, 25, 120, 30);
    self.segment.selectedSegmentIndex = 0;
    [self.segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = self.segment;
}

// segment点击事件
- (void)segmentAction:(UISegmentedControl *)segment{
    if (segment.selectedSegmentIndex == 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"remove" object:nil];
    }
    else if (segment.selectedSegmentIndex == 1){
        MyFriendsViewController *myFriendsvc = [[MyFriendsViewController alloc] initWithNibName:@"MyFriendsViewController" bundle:nil];
        [self addChildViewController:myFriendsvc];
        [self.view addSubview:myFriendsvc.view];
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.modelArray.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    FriendsMainModel *model = self.modelArray[section];
    return model.movieArray.count;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 15, 10);
}
// cell间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
// item得大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = (KWIDTH - 40) / 3;
    return CGSizeMake(width, width * 92 / 67);
}
// headerView的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(KWIDTH, 56);
}
// headerView
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *resuableView = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        FriendsHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"friendsHeaderView" forIndexPath:indexPath];
        
        FriendsMainModel *model = self.modelArray[indexPath.section];
        [headerView configureHeaderWithModel:model];
        headerView.delegate = self;
        return headerView;
    }
    return resuableView;
}

- (void)pushToPersonInfoVc:(FriendsMainModel *)model{
    PersonInfoViewController *personInfoVc = [[PersonInfoViewController alloc] initWithNibName:@"PersonInfoViewController" bundle:nil];
    personInfoVc.uid = model.uid;
    personInfoVc.header = model.header;
    personInfoVc.username = model.username;
    personInfoVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:personInfoVc animated:YES];
    
}

// item
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    FriendsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"friendsCell" forIndexPath:indexPath];
    FriendsMainModel *model = self.modelArray[indexPath.section];
    FriendsMovieInfoModel *movieModel = model.movieArray[indexPath.row];
    [cell configueCellWithModel:movieModel];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
